package proxy;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.proxy.Proxy;
import us.codecraft.webmagic.proxy.ProxyProvider;

import java.io.IOException;

public class NiuMoYunProxyProvider implements ProxyProvider {
    public NiuMoYunProxyProvider(){

    }
    @Override
    public void returnProxy(Proxy proxy, Page page, Task task) {
        //Donothing
    }
    @Override
    public Proxy getProxy(Task task) {
        return getRandomProxy();
    }
    private Proxy getRandomProxy(){

        CloseableHttpClient httpClient = HttpClients.createDefault();
        //ip池的代理
        HttpGet get = new HttpGet("http://api.http.niumoyun.com/v1/http/ip/get?p_id=1541&s_id=1&u=DW4EZwcyVDJaa1F-UB5Qbw8gBztRaQobBFNZXQIE&number=1&port=1&type=1&map=1&pro=0&city=0&pb=1&mr=3&cs=1");
        CloseableHttpResponse response = null;
        String Host="";
        int port=0;
        try {
            response = httpClient.execute(get);
            if(response != null && response.getStatusLine().getStatusCode() == 200)
            {
                HttpEntity entity  = response.getEntity();
                String content= EntityUtils.toString(entity);
                String[] ls = content.split(":");
                Host = ls[0];
                port = Integer.parseInt(ls[1]);
                System.out.println(Host+":"+String.valueOf(port));

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Proxy proxy = new Proxy(Host,port);
        return proxy;
    }
}
